
local _M = {}

function _M.new(key, server_list)

    local servers = {}
    local total_weight = 0

    for key, val in pairs(server_list) do

        total_weight = total_weight + val
        
        servers[#servers + 1] = {
            data = key,    -- 服务器信息（如地址、端口等）
            weight = val,
            current_weight = 0
        }

    end

    local rr_obj = {servers = servers, server_list = server_list, total_weight = total_weight}

    _M[key] = rr_obj

    return _M
end

function _M.find(key)
    
    local rr_obj = _M[key] 
    local servers = rr_obj.servers

    local selected_server = nil
    local max_weight = -math.huge

    -- 遍历并更新权重，找出最大 current_weight
    for _, server in ipairs(servers) do
        server.current_weight = server.current_weight + server.weight
        if server.current_weight > max_weight then
            max_weight = server.current_weight
            selected_server = server
        end
    end

    -- 更新选中服务器的当前权重
    if selected_server then
        selected_server.current_weight = selected_server.current_weight - rr_obj.total_weight
        return selected_server.data
    end

    return nil -- 无可用服务器时返回（通常不会发生）

end

return _M